
package com.fire.eyes.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.fire.core.util.AjaxResult;
import com.fire.eyes.constants.ErrorCodeConstants;
import com.fire.eyes.dao.BuildingMapper;
import com.fire.eyes.dao.SiteMapper;
import com.fire.eyes.model.BuildingModel;
import com.fire.eyes.model.SiteModel;
import com.fire.eyes.service.ISiteService;

import com.fire.eyes.validation.SiteFixDTO;
import com.smartthing.rest.client.SmartThingClient;
import com.smartthing.rest.model.device.Site;
import com.smartthing.rest.model.device.SiteMapData;
import com.smartthing.rest.model.device.request.SiteCreateRequest;
import com.smartthing.spi.SmartThingException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 站点Service
 *
 * @author Matthew
 * @Date 2019-01-17 20:50
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, SiteModel> implements ISiteService{

    private static final Logger LOGGER = LoggerFactory.getLogger(SiteServiceImpl.class);

    @Autowired
    private SiteMapper siteMapper;

	@Autowired
	private BuildingMapper buildingMapper;

    @Autowired
    private SmartThingClient smartThingClient;

    @Override
    public SiteModel selectOne(SiteModel entity){
        return siteMapper.selectOne(entity);
    }

    @Override
    public List<SiteModel>selectList(SiteModel model){
        return siteMapper.selectListByModel(model);
    }

    @Override
    public Page<SiteModel> selectPage(int currentPage, int pageSize, Wrapper<SiteModel> wrapper){
        return selectPage(new Page<SiteModel>(currentPage,pageSize), wrapper);
    }

    @Override
    public Page<Map<String, Object>> selectMapsPage(int currentPage, int pageSize, Wrapper<SiteModel> wrapper){
        return selectMapsPage(new Page<SiteModel>(currentPage,pageSize), wrapper);
    }

    /**
     * 查询站点详情
     * @param siteId 站点ID
     * @return
     */
    @Override
    public Map querySiteDetail(String siteId){
        return siteMapper.querySiteDetail(siteId);
    }

    /**
     * 查询站点列表（分页）
     * @param page
     * @param column
     * @param columbValue
     * @return
     */
    @Override
    public Page<Map<String,Object>> querySiteList(Page<Map<String,Object>> page, String column, String columbValue){
        return page.setRecords(siteMapper.querySiteList(page, column, columbValue));
    }

    /**
     * 我管理的维保公司（分页）
     * @param page
     * @param supervisorId
     * @return
     */
    @Override
    public Page<Map<String,Object>> queryMyMaitainorsList(Page<Map<String,Object>> page, String supervisorId){
        return page.setRecords(siteMapper.queryMyMaitainorsList(page, supervisorId));
    }

    /**
     * 我管理的业主单位（分页）
     * @param page
     * @param supervisorId
     * @return
     */
    @Override
    public Page<Map<String,Object>> queryMyProprietorsList(Page<Map<String,Object>> page, String supervisorId){
        return page.setRecords(siteMapper.queryMyProprietorsList(page, supervisorId));
    }


    @Override
    public AjaxResult siteFix(SiteFixDTO siteFixDTO){
        AjaxResult result = null;
        try {
        	// 获取站点信息
	        LOGGER.info("获取站点信息");
	        Wrapper siteWrapper = new EntityWrapper();
	        siteWrapper.eq("buildingid",siteFixDTO.getBuildid());
	        List<SiteModel> siteList = siteMapper.selectList(siteWrapper);
	        if(siteList.size() != 1){
		        LOGGER.error("建筑ID对应站点数为"+siteList.size());
		        return new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
	        }
	        SiteModel site = siteList.get(0);
            // 准备调用smartThing数据
	        LOGGER.info("获取SmartThing站点信息");
	        Site smartThingSite = smartThingClient.getSiteByToken(site.getSitetoken());
            // 调用smartThing
            SiteCreateRequest request = new SiteCreateRequest();
            // 站点详情
	        LOGGER.info("回填站点信息入请求参数");
            request.setToken(smartThingSite.getToken());
            request.setName(smartThingSite.getName());
            request.setImageUrl(smartThingSite.getImageUrl());
            request.setDescription(smartThingSite.getDescription());
	        // 元数据
	        request.setMetadata(smartThingSite.getMetadata());

	        // 地图信息
	        LOGGER.info("填充位置信息入请求参数");
	        String mapDataType = "openstreetmap";
	        SiteMapData siteMapData = new SiteMapData();
	        siteMapData.setType(mapDataType);
	        // 建筑物表取经纬度信息
	        if(StringUtils.isEmpty(siteFixDTO.getLatitude()) || StringUtils.isEmpty(siteFixDTO.getLongitude())){
		        LOGGER.error("站点位置信息为空");
	        	return new AjaxResult(ErrorCodeConstants.PRODUCT_PARAMERROR, "站点信息校准失败", "站点信息校准失败");
	        }
	        siteMapData.addOrReplaceMetadata("zoomLevel","15");
	        siteMapData.addOrReplaceMetadata("centerLatitude",siteFixDTO.getLatitude());
	        siteMapData.addOrReplaceMetadata("centerLongitude",siteFixDTO.getLongitude());
	        request.setMap(siteMapData);

	        LOGGER.info("更新SmartThing");
            smartThingSite = smartThingClient.updateSite(smartThingSite.getToken(),request);
	        LOGGER.info("更新SmartThing成功");
            // 成功调用smartThing后数据写入数据库
	        LOGGER.info("准备更新building表");
	        BuildingModel building = new BuildingModel();
	        building.setAddress(siteFixDTO.getAddress());
	        building.setBuildimageurl(siteFixDTO.getBuildimageurl());
	        building.setBuildingname(siteFixDTO.getBuildname());
	        building.setLongitude(siteFixDTO.getLatitude());
	        building.setLevation(siteFixDTO.getLevation());
	        building.setLongitude(siteFixDTO.getLongitude());
	        Wrapper buildingWrapper = new EntityWrapper();
	        buildingWrapper.eq("buldingid",siteFixDTO.getBuildid());
	        LOGGER.info("更新building表");
	        buildingMapper.update(building,buildingWrapper);

            result = new AjaxResult(ErrorCodeConstants.SUCCESS, "站点信息校准成功", "站点信息校准成功");
        } catch (SmartThingException e) {
            LOGGER.error("SiteServiceImpl.addSite().error  错误为：", e);
            result = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
        }
        return result;
    }

}
